#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <string>

#define SPACE " "
#define SPACELEN sizeof(SPACE)

// 客户端发送的格式/服务器接收的格式
class Request
{
public:
    Request()
    {
    }

    std::string serialize() // 序列化为字符串类型
    {
        std::string str;
        str += std::to_string(_x);
        str += SPACE;
        str += _op;
        str += SPACE;
        str += std::to_string(_y);

        return str;
    }

    bool unserialize(std::string str) // "123" "+" "456"
    {
        size_t left = str.find(SPACE);
        if (left == std::string::npos)
            return false;
        _x = atoi(str.substr(0, left).c_str());

        size_t right = str.rfind(SPACE);
        if (right == std::string::npos)
            return false;
        _y = atoi(str.substr(right + 1).c_str());

        _op = str[left + 1];

        return true;
    }

public:
    int _x;
    int _y;
    char _op;
};

// 客户端接收的格式/服务器发送的格式
class Response
{
public:
    Response() {}

    Response(int result, int code)
        : _result(result), _code(code)
    {
    }

    std::string serialize()
    {
        std::string str;
        str += std::to_string(_result);
        str += SPACE;
        str += std::to_string(_code);

        return str;
    }

    bool unserialize(std::string str) // "2" "0"
    {
        int pos = str.find(SPACE);
        if (pos == std::string::npos)
            return false;

        _result = atoi(str.substr(0, pos).c_str());
        _code = atoi(str.substr(pos + 1).c_str());

        return true;
    }

public:
    int _result;
    int _code;
};

bool Recv(int sockId, std::string *str) // str 输出型参数
{
    char inbuffer[1024];
    ssize_t s = recv(sockId, inbuffer, sizeof(inbuffer) - 1, 0);
    if (s > 0)
    {
        inbuffer[s] = 0;
        *str += inbuffer;

        return true;
    }
    return false;
}

bool Send(int sockId, std::string outbuffer)
{
    ssize_t s = send(sockId, outbuffer.c_str(), outbuffer.size(), 0);
    if (s > 0)
    {
        return true;
    }
    return false;
}